package gui.cen.read;

import core.tree.Vertex;
import gui.cen.Center;
import gui.utils.Para;
import javax.swing.*;
import java.awt.*;
import java.lang.Math.*;
import java.awt.Font.*;
import java.awt.Graphics2D.*;

/*Author: John Archer, Contact: john.archer.jpa@gmail.com*/
public class TreeDar extends JPanel{

    public TreeDar() {
        this.setBorder(BorderFactory.createLineBorder(new Color(178, 178, 178), 2));
        this.setPreferredSize(new Dimension(Center.WIDGE_WIDTH, Center.WIDGE_WIDTH));
        this.repaint(); 
    }

    private Graphics2D bg = null;
    private Image offScreen = null;

    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        displayTree(g2);
    }

    public void updateTreedar(){try{this.repaint();}catch(Exception e){}}

    private void displayTree(Graphics2D ggg) {
        this.setLayout(new FlowLayout(){public Dimension preferredLayoutSize(Container cont) {return (new Dimension(Center.WIDGE_WIDTH, Center.WIDGE_WIDTH));}});
        offScreen = this.createImage(Center.WIDGE_WIDTH, Center.WIDGE_WIDTH);

        bg = (Graphics2D)offScreen.getGraphics();
        bg.setColor(new Color(102, 102, 102));
        bg.fillRect(0, 0, Center.WIDGE_WIDTH, Center.WIDGE_WIDTH);
        bg.setColor(new Color(178, 178, 178));
        bg.setFont(new Font("Tahoma", Font.PLAIN, 10));

        if(Para.TDAR!=null){
            Para.TDAR.setMagn(Para.TREEDAR_MAG);
            Para.TDAR.setCoords((int)(Center.WIDGE_WIDTH/2), (int)(Center.WIDGE_WIDTH/2));
            displayNodes(Para.TDAR.getRoot());
            bg.drawString("Location " + Para.TPOS + " to " + (Para.TPOS + Para.TREEDAR_WIN)+ ", No. of tips: " + (Para.TDAR.getNumberOfLeaves() + 1) , 4, 194);
        }
        else{
            bg.drawString("Location " + Para.TPOS + " to " + (Para.TPOS + Para.TREEDAR_WIN)+ ", No. of tips: < 5" , 4, 194);
        }
        ggg.drawImage(offScreen, 0, 0, Center.WIDGE_WIDTH, Center.WIDGE_WIDTH, this);
    }


    private void displayNodes(Vertex v) {
        Object[] children = v.getChildren().toArray();
        Vertex child;
        for (int i = 0; i != children.length; i++) {
            child = (Vertex) children[i];
            bg.drawLine(child.getX(), child.getY(), child.ptrToParent().getX(), child.ptrToParent().getY());
            if(child.getNoOfChildren() > 0){displayNodes(child);}
        }
    }  
}